﻿using SharpConfig;

namespace SyncFileCommon.BLL
{
    public class ConfigBLL
    {
        /// <summary>
        /// 配置信息
        /// </summary>
        public static ConfigModel ServiceConfig;

        public static string ConfigFilePath = System.AppDomain.CurrentDomain.BaseDirectory + "\\" + System.Diagnostics.Process.GetCurrentProcess().ProcessName + @"Config.ini";

        /// <summary>
        /// 加载配置文件信息
        /// </summary>
        /// <param name="configPath"></param>
        /// <returns></returns>
        public static bool LoadConfig(string configPath = "")
        {
            if (!string.IsNullOrWhiteSpace(configPath))
            {
                ConfigFilePath = configPath;
            }

            string _configValue = string.Empty;

            if (File.Exists(ConfigFilePath))
            {
                _configValue = File.ReadAllText(ConfigFilePath);
            }

            if (string.IsNullOrWhiteSpace(_configValue))
            {
                ServiceConfig = new ConfigModel();
                
                SaveConfig();
                return false;
            }
            else
            {
                Configuration _cfg = Configuration.LoadFromString(_configValue);
                ServiceConfig = _cfg["Service"].ToObject<ConfigModel>();
                

                _cfg = new Configuration();
                _cfg.Add(Section.FromObject("Service", ServiceConfig), "服务端配置"); 

                if (_configValue != _cfg.StringRepresentation)
                {
                    SaveConfig();
                }
                return true;
            }

        }

        /// <summary>
        /// 保存配置文件信息
        /// </summary>
        public static void SaveConfig()
        {
            if (string.IsNullOrWhiteSpace(ConfigFilePath))
            {
                return;
            }

            if (File.Exists(ConfigFilePath))
            {
                File.Delete(ConfigFilePath);
            }

            if (ServiceConfig == null)
            {
                ServiceConfig = new ConfigModel();
            }

          

            Configuration _cfg = new Configuration();
            _cfg.Add(Section.FromObject("Service", ServiceConfig), "配置信息"); 
            _cfg.SaveToFile(ConfigFilePath);
        }


    }

    /// <summary>
    /// 配置信息
    /// </summary>
    public class ConfigModel
    {
         
        [SharpConfig.Comment("远程服务地址")]
        public string ServiceURL { get; set; } = "";

        [SharpConfig.Comment("远程服务加密公钥")]
        public string ServicePublicKey { get; set; } = "";

    }

     

}
